package com.java.controller;

import com.java.model.Result;
import com.java.model.User;
import com.java.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/user")
public class AdminController {

    @Autowired
    private UserService userService;

    /**
     * 跳转管理员管理页面
     * @return
     */
    @GetMapping("/list")
    public String list() {
        return "/user/list";
    }

    /**
     * 查询管理员列表
     * @param user
     * @return
     */
    @PostMapping("/toList")
    @ResponseBody
    public Result toList(User user) {
        return userService.list(user);
    }

    /**
     * 跳转新增页面
     * @return
     */
    @GetMapping("/add")
    public String add() {
        return "/user/add";
    }

    /**
     * 新增
     * @param user
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public Result save(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    /**
     * 跳转到管理员修改
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/edit")
    public String edit(int id, Model model) {
        Result result = userService.get(id);
        if (result.getCode().equals("0")) {
            model.addAttribute("user", result.getData());
        }

        return "/user/edit";
    }

    /**
     * 修改管理员
     * @param user
     * @return
     */
    @PostMapping("/modify")
    @ResponseBody
    public Result remove(@RequestBody User user) {
        userService.modify(user);
        return Result.success();
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public Result remove(int[] ids) {
        userService.remove(ids);
        return Result.success();
    }


    /**
     * 分配角色页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editRole")
    public String editRole(Model model, int id) {
        model.addAttribute("id", id);
        return "user/editRole";
    }

    @GetMapping("/listRole")
    @ResponseBody
    public Result listRole(int userId) {
        return userService.listRole(userId);
    }
}
